import router from '@/router';
import { clearStorage, getStorage, setStorage } from '@/utils/storage';
import { defineStore } from 'pinia';
import { isNotBlank } from '@/utils';
import { AUTH_TOKEN_KEY } from '@/config/constant';
import { LOGIN_ROUTE_NAME } from '@/router/static';

export interface UserState {
    token: string | null
}

export const useUserStore = defineStore('user', {
    state: (): UserState => {
        return {
            token: getStorage(AUTH_TOKEN_KEY),
        }
    },
    getters: {
        getToken: (state): string | null => state.token || getStorage(AUTH_TOKEN_KEY) || null,
        isLoggedIn: (state): boolean => isNotBlank(state.token)
    },
    actions: {
        setToken(token: string | null) {
            this.token = token
            setStorage(AUTH_TOKEN_KEY, token);
        },
        logout() {
            this.setToken(null)
            clearStorage()
            router.replace({
                name: LOGIN_ROUTE_NAME,
                query: { redirect: router.currentRoute.value.fullPath }
            })
        }
    }
})
